<template>
  <div class="app-container">

    <!-- 列表 -->
    <unk-table :data="unkTable" v-if="flag"></unk-table>
    <!-- 导入 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" :close-on-click-modal="false"
      :close-on-press-escape="false" width="400px" append-to-body>
      <el-upload ref="upload" class="upload-demo" drag multiple :auto-upload="false" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :on-success="handlefileSuccess" :limit="3"
        accept=".xlsx, .xls">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
          <el-link type="info" style="font-size: 12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导入结束 -->

    <!-- 新增 -->
    <el-dialog title="新增" :visible.sync="dialogFormVisible" :close-on-click-modal="false"
      :close-on-press-escape="false" width="800px">
      <unk-form :data="unkForm" v-if="formShow"></unk-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeinfostu" v-if="this.isdata == 1">关闭</el-button>
        <div v-else>
          <el-button @click="closedialog()">取 消</el-button>
          <el-button type="primary" @click="confirmadd">确 定</el-button>
        </div>
      </div>
    </el-dialog>
    <img src="" alt="" />
  </div>
</template>

<script>
import { getstudentslist, downloadfile } from "unkApi/system/parmanagement";
import { getschoollist, getclasslist } from "unkApi/system/class";
import {
  delectStudentInfo,
  addStudent,
  classHistory,
  delStudent,
  improveInfo
} from "@/api/system/studentmove";
import { getToken } from "@/utils/auth";
import { exportUser, importTemplate } from "@/api/system/user";
import headimg from "../../../assets/image/selfphone.png";
import idcard from "../../../assets/image/identity.png";
import idcards from "../../../assets/image/identity2.png";
export default {
  data() {
    return {
      url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
      srcList: [],
      jgname: [],
      formShow: false,
      classlist: [],
      windowstatus: "",  //新增和完善资料状态 0是新增，1是完善
      //完善资料和查看资料判断
      isdata: "",
      flag: false,     //0是未认证，就是查看资料，1是已认证，就是完善资料
      isdisable: true,   //是否禁止上传
      schoollistarr: [],
      //新增弹窗form
      headsrc: headimg, //新增 头像封面
      unkForm: {
        formOption: [],
        requestOption: {},
        rules:[]
      },
      unkTable: {
        total: 0,
        tableData: [],
        tableOption: [],
        searchData: [],
        tableOptionSave: [],
        //操作栏配置参数
        tableBarOption: [],
        //工具栏配置参数
        tableButtonOption: [],
        isBar: false,
        isBarShow: false,
        //搜索区域
        tableLoadOption: {
          pageNum: 1,
          pageSize: 10,
          status: "",
          schoolName: "",
          className: "",
          userName: "", //名称
          phonenumber: "", //手机号
          idCardNo: "", //身份证号
          statusval: "",
          deptId: "",
          classId: ""
        }
      },
      idcard: idcard, //新增 身份证正面封面
      idcards: idcards, //新增 身份证反面封面
      addstuform: {
        name: "",
        sex: "",
        idCardNo: "",
        address: "",
        phonenum: "",
        schoolId: "",
        deptName: "",
        userId: "",
        imageUrl4: "",
        imageUrl5: "",
        imageUrl6: "",
      },
      //查看资料

      rules: {
        phonenum: [
          { required: true, message: "请输入手机号", trigger: "blur" },
        ],
        deptName: [{ required: true, message: "请选择学校", trigger: "change" },],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
        idCardNo: [
          { required: true, message: "请输入身份证号", trigger: "blur" },
        ],
        address: [{ required: true, message: "请输入籍贯", trigger: "blur" }],
        imageUrl4: [{ required: true, message: "请上传头像", trigger: "blur" }],
        imageUrl5: [{ required: true, message: "请上传身份证正面照", trigger: "blur" }],
        imageUrl6: [{ required: true, message: "请上传身份证反面照", trigger: "blur" }],
      },
      dialogFormVisible: false,
      isvisible: true, //是否显示操作

      addfileData: {
        userId: "",
        uploadType: "",
      },
      addheadimgurl: undefined,
      fileUploadheaders: {
        Authorization: "Bearer " + getToken(),
      },
      uploadSign: null,

      // 新增

      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/business/student/importData",
      },
      // 总条数
      total: 0,
      options: [
        //专业
        {
          id: 0,
          value: "启用",
        },
        {
          id: 1,
          value: "停用",
        },
      ],

      classtitle: "课次管理",
      title: "新增",
      changetitle: "修改",
      studenttitle: "查看资料",
      historyClass: "历史班期",
      open: false, //新增弹窗
      changeopen: false, //修改弹窗
      studentopen: false, //查看弹窗
      historyDialog: false, //查看历史弹窗
      classopen: false, //课次管理

      tableData: [],
      tableHistoryData: [],

      multipleSelection: [],
      userIDbox: {
        userId: "",
      },
      comfirm: {
        phoneNo: "",
        userId: "",
      },
    };
  },
  created() {
    var className = this.$route.params.className;
    var schoolName = this.$route.params.schoolName;
    if (className !== undefined || schoolName !== undefined) {
      this.tableLoadData.schoolName = schoolName;
      this.tableLoadData.className = className;
      getstudentslist(this.tableLoadData).then((response) => {

        console.log(response);
        this.tableData = response.rows;
        this.total = response.total;
      });
    } else {
      this.tableLoad(this.unkTable.tableLoadOption);
    }
    var data = JSON.parse(localStorage.getItem("permissions"));
    console.log(data);
    //this.getschoollist()
  },
  methods: {
    //获取学校id
    getschoolid(id) {
      console.log(id);
      this.tableLoadData.schoolId = id;
      getclasslist(this.tableLoadData).then((res) => {
        console.log(res);
        this.classlist = res;
      });
    },
    gettest() {
      this.$emit()
    },
    // 获取班期Id
    getclassid(id) {
      console.log(id);
      this.tableLoadData.classId = id;
    },

    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then((response) => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },


    //上传图片成功时（新增）
    addhandleAvatarSuccess(res, file) {
      console.log(res, file);
      if (this.uploadSign === 4) {
        if (res.code == 200) {
          this.$alert("上传成功");
          this.addstuform.imageUrl4 = URL.createObjectURL(file.raw);
        } else {
          this.$message.error(res.msg);
        }
      } else if (this.uploadSign === 5) {
        if (res.code == 200) {
          this.$alert("上传成功");
          this.addstuform.imageUrl5 = URL.createObjectURL(file.raw);
          //身份证上传后，后台redis存储的图片key值
          this.addstuform.timestamp = res.timestamp;
        } else {
          this.$message.error(res.msg || "上传失败");
        }
        if (res.code == 200) {
          if (res.sex == "0") {
            res.sex = "0";
          } else {
            res.sex = "1";
          }
          this.addstuform.name = res.name;
          this.addstuform.sex = res.sex;
          this.addstuform.idCardNo = res.idCardNo;
          this.addstuform.address = res.address;
        }
      } else if (this.uploadSign === 6) {
        if (res.code == 200) {
          this.$alert("上传成功");
          this.addstuform.imageUrl6 = URL.createObjectURL(file.raw);
          //身份证上传后，后台redis存储的图片key值
          this.addstuform.timestamp = res.timestamp;
        } else {
          this.$alert("上传失败");
        }
      }
      this.tableLoad();
    },
    //上传之前（新增）
    addbeforeAvatarUpload(file) {
      if (this.uploadSign === 4) {
        this.addfileData.uploadType = 0;
        if (this.addstuform.timestamp) {
          //身份证上传后，后台redis存储的图片key值
          this.addfileData.timestamp = this.addstuform.timestamp;
        }
      }
      if (this.uploadSign === 5) {
        this.addfileData.uploadType = 1;
        if (this.addstuform.timestamp) {
          //身份证上传后，后台redis存储的图片key值
          this.addfileData.timestamp = this.addstuform.timestamp;
        }
      }
      if (this.uploadSign === 6) {
        this.addfileData.uploadType = 2;
        if (this.addstuform.timestamp) {
          //身份证上传后，后台redis存储的图片key值
          this.addfileData.timestamp = this.addstuform.timestamp;
        }
      }
      const istype = file.type == "image/jpeg" || file.type == "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!istype) {
        this.$message.error("上传的图片只能是 JPG 格式或 PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return istype && isLt2M;
    },

    //关闭弹窗
    close() {
      this.upload.open = false;
      this.tableLoad();
    },
    //文件上传成功后的回调
    handlefileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.tableLoad();
    },
    initTableComp() {
      if (_this.$store.state.student.saveData.length == 0) {
        _this.$store.state.student.saveData.forEach(item => {
          _this.$store.state.student.saveData.push(item)
        })
      }
    },
    choosestatus(id) {
      console.log(id);
      this.tableLoadData.status = id;
    },
    saveTableOptionSave(getCheckedNodes) {
      this.$store.state.student.tableOptionSave = getCheckedNodes
      this.$store.commit("setTableOptionSave", this.$store.state.student.tableOptionSave)
      this.unkTable.tableOptionSave = this.$store.state.student.tableOptionSave
      this.tableHeaderUpdate = false
    },
    //加载表格数据和配置
    tableLoad(tableLoadOption) {
      let _this = this;
      getstudentslist(tableLoadOption).then((response) => {
        console.log(response);
        //传递给table公共组件数据
        _this.unkTable.tableData = response.rows;
        //传递给table公共组件表格配置
        _this.unkTable.tableOption = _this.$store.state.student.tableOption
        //如果是第一次加载页面
        if (_this.unkTable.searchData.length == 0) {
          //传递给table公共组件需要搜索的表格配置
          _this.unkTable.tableOption.forEach((item, index) => {
            if (item.search == true) {
              _this.unkTable.searchData.push(item)
            }
          })
          //遍历传递给table公共组件需要搜索的下拉菜单的数据
          _this.unkTable.searchData.forEach((item, index) => {
            if (item.type == "select") {
              if(item.selectOption!=undefined && item.selectOption!= null && item.selectOption!=""){
                item.selectOptionValue = _this.$store.state[item.selectOption].cacheData.rows
              }
            }
          })
        }
        //如果用户还没有编辑过列
        if (_this.$store.state.student.tableOptionSave.length == 0) {
          //传递给table公共组件表格的配置 全部显示
          _this.unkTable.tableOptionSave = _this.$store.state.student.tableOption
        } else {
          //传递给table公共组件上次的配置 显示上次配置
          _this.unkTable.tableOptionSave = _this.$store.state.student.saveKeyValue
        }
        //传递给table公共组件表格数据条数
        _this.unkTable.total = response.total
        //是否展示操作栏
        _this.unkTable.isBar = _this.$store.state.student.isBar
        //操作栏
        _this.unkTable.tableBarOption = _this.$store.state.student.tableBarOption
        //工具栏
        _this.unkTable.tableButtonOption = _this.$store.state.student.tableButtonOption
        //数据传递完才加载table公共组件
        this.flag = true
        //加载form
        _this.$store.state.student.formOption.forEach((item, index) => {
          if (item.state) {
            _this.unkForm.formOption.push(item)
            _this.unkForm.rules.push({
              [item.key]:[
                {
                  required:item.required,
                  trigger: item.trigger
                }
              ]
            })
          }
        })
        //遍历传递给form公共组件需要搜索的下拉菜单的数据
        _this.unkForm.formOption.forEach((item, index) => {
          if (item.type == "select") {
            item.selectOptionValue = _this.$store.state[item.selectOption].cacheData.rows
          }
        })
        this.formShow = true
      });
    },
    // 认证状态
    isAttestation(row, column) {
      return row.authentication == "0"
        ? "未认证"
        : row.authentication == "1"
          ? "已认证"
          : "";
    },
    //性别
    formatter(row, column) {
      return row.sex == "0" ? "男" : "女";
    },
    //列表
    // getstudentslist() {
    //   getstudentslist().then((response) => {
    //     alert(1);
    //     console.log(response);
    //     this.tableData = response.rows;
    //   });
    // },
    //重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
      (this.tableLoadData.schoolName = ""), (this.tableLoadData.className = "");
    },

    //删除
    deletestudents(studentId, index) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delStudent([studentId]).then((response) => {
            if (response.code == 200) {
              this.tableData.splice(index, 1);
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            } else {
              this.$message.error('删除失败');
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //新增
    add() {
      this.open = true;
    },

    // 取消添加
    canceladd() {
      this.open = false;
      this.changeopen = false;
      this.studentopen = false;
      this.historyDialog = false;
    },
    //修改
    change() {
      this.changeopen = true;
    },
    clearisdata() {
      this.addstuform.schoolId = "",
        this.addstuform.deptName = "",
        this.addstuform.address = ""
      this.addstuform.imageUrl4 = ""
      this.addstuform.imageUrl5 = ""
      this.addstuform.imageUrl6 = ""
      this.addstuform.name = ""
      this.addstuform.idCardNo = ""
      this.addstuform.phonenum = ""
      this.addstuform.sex = ""
      // this.addfileData.userId = "";
    },
    //完善资料关闭弹窗
    closeinfostu() {
      this.clearadd()
    },
    clickFunc(type, row, index) {
      switch (type) {
        case "select":
          this.perfecttheinformation(row)
          break;
        case "edit":
          this.perfecttheinformation(row)
          break;
        case "remove":
          this.deletestudents(row.studentId, index)
          break;
        case "add":
          this.addstudent(row.studentId, index)
          break;
        default:
          return
      }
    },
    //完善资料,查看资料
    perfecttheinformation(row) {
      this.dialogFormVisible = true;
      this.addheadimgurl = process.env.VUE_APP_BASE_API + "/business/student/improveInfo";
      this.addfileData.userId = row.userId
      if (row.authentication == 0) {
        this.clearisdata()
        this.isdata = 0;
        this.isdisable = false    //未认证状态
      } else {
        console.log(this.schoollistarr)
        var schoollist = this.schoollistarr
        for (let i = 0; i < schoollist.length; i++) {
          if (row.deptId = schoollist[i].deptId) {
            this.addstuform.deptName = schoollist[i].deptName
            this.addstuform.schoolId = row.deptId
          }
        }
        this.isdata = 1;
        this.isdisable = true      //已经认证状态
        this.addstuform.address = row.address
        this.addstuform.imageUrl4 = row.avatar
        this.addstuform.imageUrl5 = row.idCardFront
        this.addstuform.imageUrl6 = row.idCardBack
        this.addstuform.name = row.nickName
        this.addstuform.idCardNo = row.idCardNo
        this.addstuform.phonenum = row.phonenumber
        if (row.sex == "0") {
          this.addstuform.sex = "0";
        } else {
          this.addstuform.sex = "1";
        }
      }
    },
    //导入
    handleImport() {
      this.upload.open = true;
    },
    //提交上传导入
    submitFileForm() {
      this.$refs.upload.submit();
    },

    /** 导出按钮操作 */
    handleExport() {
      this.$confirm("是否确认导出所有用户数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return downloadfile();
        })
        .then((response) => {
          this.download(response.msg);
        })
        .catch(function () { });
    },

    // 查看历史班级
    watchHistoryClass(row) {
      if (row.history == "否") {
        this.$message({
          message: "暂无数据",
          type: "success",
        });
      } else if (row.history == "是") {
        this.historyDialog = true;
        this.tableHistoryData = [];
        var that = this;
        classHistory(row.studentId).then((res) => {
          var arr = res;
          for (var i = 0; i < res.length; i++) {
            // this.tableHistoryData.push({ historyClass: res[i] });
            this.tableHistoryData.push({ historyClass: res[i].className });
            // that.tableHistoryData.push(res[i].className);
          }
        });
      }
    },

    //查看 跳转
    watchstudent(row) {
      console.log(row);
      var phonenumber = row.phonenumber;
      var idCardNo = row.idCardNo;
      var userName = row.nickName;
      this.$router.push({
        name: "/",
        params: {
          phonenumber,
          idCardNo,
          userName,
        },
      });
    },
    //删除
    deleteRow(studentId) {
      // delStudent([studentId]).then((response) => {
      //   if (response.code == 200) {
      //     this.$message("删除成功");
      //   }
      // });
    },

    //考勤管理 跳转
    studentatt(row) {
      console.log(row)
      var userName = row.nickName;
      console.log(userName)
      this.$router.push({
        name: "/att",
        params: {
          nickName: userName
        },
      });
    },

    //新增
    addstudent() {
      this.dialogFormVisible = true
      this.clearadd()
    },
    //取消增加
    closedialog() {
      this.clearadd();
      delectStudentInfo(this.userIDbox).then((response) => {
        console.log(response);
        // this.$message("已取消添加");
      });
    },
    // 清空新增
    clearadd() {
      this.$store.state.student.formOption.forEach((item, index) => {
        item.value = ""
      })
    },
    //确定新增
    confirmadd() {
      this.unkForm
      var formData = new FormData();
      formData.append("phoneNo", this.$store.state.student.formOption.phonenumber);
      formData.append("uploadType", this.$store.state.student.formOption.uploadType);
      formData.append("timestamp", this.$store.state.student.formOption.timestamp);
      formData.append("schoolId", this.$store.state.student.formOption.school.id);
      this.$refs.addstuform.validate((valid) => {
        if (valid) {
          addStudent(formData).then((response) => {
            console.log(response);
            if (response.code == 200) {
              this.$message({
                message: "新增成功",
                type: "success",
              });
              this.tableLoad();
              this.clearadd();
            } else {
              this.$message.error(response.msg || "新增失败");
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //点击学校获取学校id
    getdeptid(id) {
      console.log(id)
      this.addstuform.schoolId = id
      console.log(this.addstuform)
    }
  },
  mounted() { },
};
</script>
<style  scoped>
.el-form-item__content {
  width: 495px !important;
}
.el-table::before {
  height: 0px;
}
#allmap {
  width: 100%;
  height: 500px;
}

.demonstration {
  width: 100px;
  line-height: 36px;
  display: inline-block;
  text-align: right;
  padding: 0 12px 0 0;
  box-sizing: border-box;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
.identityzheng {
  width: 380px;
  height: 200px;
  object-fit: cover;
}

.el-upload__tip {
  margin-left: 20px;
}
.head {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 100%;
}
/deep/.headsrc label {
  height: 80px !important;
  line-height: 80px !important;
}

.headimgs {
  width: 80px;
  height: 80px;
  position: relative;
  border-radius: 100%;
}
.el-icon-plus {
  width: 80px;
  height: 80px;
}
.el-icon-plus:before {
  content: "";
}

.headpic {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.identityposter {
  width: 270px;
  height: 100%;
  object-fit: cover;
}
/deep/.idcards .el-upload {
  height: 170px !important;
  border-radius: 8px;
}
.idcardbox {
  display: flex;
  justify-content: space-between;
}
.uploadidcard {
  text-align: center;
  width: 100%;
  display: block;
  margin: 10px 0px;
  font-size: 16px;
}
.studentimg {
  width: 110px;
  height: 133px;
}
/deep/.el-image__inner {
  object-fit: cover;
}

/deep/.el-icon-circle-close:before {
  color: #fff;
}
</style>
